package com.launch.wlfw.interceptor;

import org.apache.log4j.Logger;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author: Liu Yuehui
 * @ClassName: LoginInterceptor
 * @date: 2023/6/30 10:56
 * @description: 拦截器
 * @version： v1：2023/6/30 10:56：
 **/
public class LoginInterceptor implements HandlerInterceptor {

    private static final Logger logger = Logger.getLogger(LoginInterceptor.class);

    @Resource
    private RedisTemplate<String , Object> redisTemplate;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //在处理过程中进行拦截
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 已经登录了就放行 否则进行拦截
        HttpSession session=request.getSession();
        if(session.getAttribute("username") != null){
            String username = session.getAttribute("username").toString();

            logger.info("前端获取到的session——ID : " + session.getId());

            if(Boolean.TRUE.equals(redisTemplate.hasKey(username))){
                String cacheSessionId = String.valueOf(redisTemplate.opsForValue().get(username));
                logger.info("缓存中获取到的session——ID : " + cacheSessionId);
                if (session.getId().equals(cacheSessionId)) {
                    return true;
                }
            }
        }

        //没有登录 跳转到登录页面进行登录操作
        response.sendRedirect(request.getContextPath()+"/login");
        return false;
    }
}
